import serial
import struct
import binascii
import multiprocessing
import sys
import logging
import time
import traceback
from multiprocessing import Process, Queue
import subprocess 
import os
import json
import asyncio
import http.client
import urllib
import socket
import time
import select
from time import ctime
OBJ_HOST = "localhost"
OBJ_URL = "/remotestation/message"
PORT = 80

CWD_DIR = os.path.split(os.path.abspath(__file__) )[0]


class check(object):
	def __init__(self,checkTuple):
		self.power = checkTuple[0]
		self.name = checkTuple[1]
		self.state = checkTuple[2]
		self.id = 1234

def check_to_json(r):
	return{
	    'power':r.power,
		'name':r.name,
		'state':r.state,
		'id':r.id
	}

def list_to_json(listData):
	if not isinstance(listData, (list, tuple)):
		raise TypeError('bad operand type, parameter must be a tuple or list')
	list_json = []
	#for elem in listData:
	list_json.append(check(listData))
	dataJson = json.dumps(list_json,default=check_to_json,ensure_ascii=False)
	return dataJson

def httpSend(host, url, port, data_str):
	conn = http.client.HTTPConnection(host, port, timeout = 5)
	data = {'data':data_str}
	headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "*/*"}
	params = urllib.parse.urlencode(data)
	conn.request("POST", url, params, headers)

	response = conn.getresponse()
	data = response.read()
	conn.close()
	return data

def recv(serialPort):
	data_list = []	
	data_num = 0
	data_byte = serialPort.read(1)
	data_bytes = data_byte
	data_num += len(data_byte)

	while data_byte == b'\xaa' :		

		data_byte = serialPort.read(75) 
		data_num += len(data_byte)
		data_bytes += data_byte
		data_list = struct.  unpack('B'*data_num, data_bytes)
		return data_list
	


def receive0(q):
	t = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
	while not t.isOpen():
		t = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
	while True:
		try:
			data = recv(t)
			if data is not None and data[1]==187:
				cmd = ('./recognize '+ '%d '*68) %(data[6:-2])
				p = subprocess.Popen(cmd , shell=True , stdout=subprocess.PIPE , cwd=CWD_DIR)
				send =[] 
				name = p.stdout.read()
				name=name.decode('utf-8')
				print("检测到数据",name)
				for elem in name.split(','):
					send.append(elem)
				dataJson = list_to_json(send)
				print("数据正在上报",dataJson)
				q.put(dataJson)
				#bendi.data_write(dataJson)#仅此一处加入存入本地
				try:
					httpSend(OBJ_HOST, OBJ_URL, PORT, dataJson)
					print("实时数据上报成功")
				except :
					print("实时数据上报失败")
				
	
		except Exception as e :
			print("error:",e)

def client(q):
    global adress,port,sock
    adress = "120.24.60.81"
    port = 10001
    sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    
    sock.connect((adress,port))
    epoll = select.epoll()
    fd = sock.fileno()
    epoll.register(fd,select.EPOLLIN)
    events = epoll.poll(1)
    while True:
    	data=q.get()
    	if len(data)>0:
	    	sock.send(('%s' % (data)).encode())
	    	print("数据已发送给了阿里云",data)
	    	datas = sock.recv(128)
	    	if len(datas) > 0:
	    		print ("收到阿里云信息",datas)

def server(p):
	global address,port,sock
	address = "0.0.0.0"  
	port = 8800 
	sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) 
	#global address,port,sock
	epoll = select.epoll()  
     #获取创建好的sock的文件描述符
	fd = sock.fileno()
	sock.bind((address,port))
	sock_dict = {}
	sock_dict[fd] = sock#对该sock进行注册
	epoll.register(fd,select.EPOLLIN)
	sock.listen(5)
	while True:
		events = epoll.poll(1)
		#获取到的文件描述符和sock的相同就说明是一个新的连接
		for fileno,event in events:
			if fileno == fd:
				(client,address) = sock.accept()
				print (address)
				client.setblocking(0)#将新的连接进行注册，用来接收消息
				epoll.register(client.fileno(),select.EPOLLIN)
				sock_dict[client.fileno()] = client
			elif event & select.EPOLLIN:
				#print ("fileno:",fileno)#返回套接字的文件描述符
				data = sock_dict[fileno].recv(128)
				if data == '你好':
					print ("Data:",data.decode('UTF-8') )
					sock_dict[fileno].send("你好")
				elif len(data) == 0:
					print ("client %d is not connected"%fileno )
					epoll.unregister(fileno)
				else:
					print ("Data:",data)
					if data==b'0':
						print("close")
						t = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
						#print(data.decode())
						#print(data)
						t1=bytes.fromhex('AA BB 00 EE FF')
						t1=t.write(t1)
						#sleep(1)
					elif data==b'1':
						print("open")
						t = serial.Serial('/dev/ttyUSB0', 115200, timeout=1)
						t1=bytes.fromhex('AA BB 01 EE FF')
						t1=t.write(t1)
					elif data==b'2':
						print("close")
						t = serial.Serial('/dev/ttyUSB1', 115200, timeout=1)
						#print(data.decode())
						#print(data)
						t1=bytes.fromhex('AA BB 00 EE FF')
						t1=t.write(t1)
					elif data==b'3':
						print("open")
						t = serial.Serial('/dev/ttyUSB1', 115200, timeout=1)
						t1=bytes.fromhex('AA BB 01 EE FF')
						t1=t.write(t1)
					elif data==b'4':
						print("close")
						t = serial.Serial('/dev/ttyUSB2', 115200, timeout=1)
						#print(data.decode())
						#print(data)
						t1=bytes.fromhex('AA BB 00 EE FF')
						t1=t.write(t1)
					elif data==b'5':
						print("open")
						t = serial.Serial('/dev/ttyUSB2', 115200, timeout=1)
						t1=bytes.fromhex('AA BB 01 EE FF')
						t1=t.write(t1)






def main():

	try:
		q = Queue()
		prev0 = Process(target=receive0, args=(q,))
		prev1 = Process(target=client, args=(q,))
		prev0.start()
		prev1.start()
	
	except:
		traceback.print_exc()

if __name__ == "__main__":
	main()


		



